package cn.lds.j375.chlm.service.impl;

import cn.lds.j375.chlm.dto.ResultDTO;
import cn.lds.j375.chlm.entity.Menu;
import cn.lds.j375.chlm.entity.Order;
import cn.lds.j375.chlm.entity.OrderDetails;
import cn.lds.j375.chlm.entity.User;
import cn.lds.j375.chlm.mapper.MenuMapper;
import cn.lds.j375.chlm.mapper.OrderDetailsMapper;
import cn.lds.j375.chlm.mapper.OrderMapper;
import cn.lds.j375.chlm.mapper.UserMapper;
import cn.lds.j375.chlm.service.OrderService;
import cn.lds.j375.chlm.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Stream;

public class OrderServiceImpl implements OrderService {

    private static SqlSession sqlSession;

    private static OrderMapper orderMapper;

    private static MenuMapper menuMapper;

    private static UserMapper userMapper;

    private static OrderDetailsMapper orderDetailsMapper;

    static {
        sqlSession = SqlSessionUtil.getSqlSession();
        orderMapper = sqlSession.getMapper(OrderMapper.class);
        orderDetailsMapper = sqlSession.getMapper(OrderDetailsMapper.class);
        menuMapper = sqlSession.getMapper(MenuMapper.class);
        userMapper = sqlSession.getMapper(UserMapper.class);
    }


    @Override
    public ResultDTO<List<Order>> selectOrderByUserId(Integer userId) {

        List<Order> orders = orderMapper.selectOrderByUserId(userId);

        if (null == orders || orders.size() ==0){
            return ResultDTO.buildError("您还没有下过单，是不是没有钱？");
        }


        return ResultDTO.buildSuccess(orders);
    }

    @Override
    public ResultDTO addOrder(Integer userId, OrderDetails... orderDetails) throws Exception {

        int r1 = 0;
        int r2 = 0;

        //定义一个变量，保存总价格
        BigDecimal totalPrice = new BigDecimal("0");
        //遍历订单详情数组
//        for (OrderDetails orderDetail : orderDetails) {
//            //获取每个菜品的id
//            Integer menuId = orderDetail.getMenuId();
//            //获取每个菜品的详情
//            Menu menu = menuMapper.selectMenuById(menuId);
//
//            BigDecimal orderDetailsPrice = menu.getPrice().multiply(new BigDecimal(orderDetail.getCount()));
//
//            totalPrice = totalPrice.add( orderDetailsPrice);
//
//        }

        try {
            //遍历传入的订单详情数组
            for (int i = 0; i < orderDetails.length; i++) {
                //获取详情中每一个菜品的id
                Integer menuId = orderDetails[i].getMenuId();
                //根据菜品id获取菜品详细信息
                Menu menu = menuMapper.selectMenuById(menuId);
                //计算想起总价
                BigDecimal orderDetailsPrice = menu.getPrice().multiply(new BigDecimal(orderDetails[i].getCount()));
                //将详情总价存入数组
                orderDetails[i].setOrderDetailPrice(orderDetailsPrice);
                //计算最终订单总价
                totalPrice = totalPrice.add( orderDetailsPrice);
            }

            //判断用户是否又足够的钱支付
            User user = userMapper.selectUserById(userId);

            if (user.getMoney().compareTo(totalPrice) < 0) {
                return ResultDTO.buildError("您的钱不够，请先去挣钱再来吃饭。");
            }
            //扣除用户的钱
            user.setMoney(user.getMoney().subtract(totalPrice));

            userMapper.modifyUser(user);

//            int i = 1/0;

            //封装总订单数据
            Order order = new Order();

            order.setUserId(userId);
            order.setTotalPrice(totalPrice);

            //将订单存入数据库
            r1 = orderMapper.addOrder(order);


            //获取订单id
            Integer orderId = order.getId();

            //封装订单详情，存入数据库
            for (OrderDetails orderDetail : orderDetails) {
                orderDetail.setOrderId(orderId);

                r2 = orderDetailsMapper.addOrderDetails(orderDetail);
            }
            sqlSession.commit();

        }catch (Exception e){
            sqlSession.rollback();
            throw new Exception();
        }finally {
            sqlSession.close();
        }


        if (r1 * r2 == 0){
            return ResultDTO.buildError();
        }

        return ResultDTO.buildSuccess();
    }
}
